#include "abstractcontainer.h"
#include "defines.h"

#include <QXmlStreamWriter>
#include <QXmlStreamReader>

AbstractContainer::AbstractContainer() :
    m_name("unknown")
{
}

AbstractContainer::AbstractContainer(const QString &name) :
    m_name(name)
{
}

AbstractContainer::AbstractContainer(AbstractContainer &container)
{
    for(int i = 0; i<container.size(); i++) {
        AbstractStorage *stor = new AbstractStorage( container.at(i) );
        this->append(stor);
    }
    setName( container.name() );
}

AbstractContainer::AbstractContainer(AbstractContainer *container)
{
    for(int i = 0; i<container->size(); i++) {
        AbstractStorage *stor = new AbstractStorage( container->at(i) );
        this->append(stor);
    }
    setName( container->name() );
}

AbstractContainer::~AbstractContainer()
{
    clear();
}

void AbstractContainer::readFromXml(QXmlStreamReader *pXml)
{    
    QString name = pXml->name().toString();
    setName(name);
    while( !(pXml->name() == name && pXml->isEndElement()) && !pXml->atEnd() ) {
        pXml->readNext();
        if( pXml->tokenType() == QXmlStreamReader::Characters ) pXml->readNext();
        if(pXml->isStartElement()) {
            AbstractStorage* storage = appendStorage(pXml->name().toString());
            storage->readFromXml(pXml);
        }
    }
}

void AbstractContainer::writeToXml(QXmlStreamWriter *pXml)
{
    if( this->size()>0 ) {
        pXml->writeStartElement( m_name );
        for( int i = 0; i < this->size(); i++ ) {
            AbstractStorage *storage = this->at(i);
            storage->writeToXml(pXml);
        }
        pXml->writeEndElement();
    }
}

void AbstractContainer::clear()
{
    for( int i = 0; i < this->size(); i++ ) {
        AbstractStorage *storage = this->at(i);
        delete storage;
    }
    QList<AbstractStorage*>::clear();
}

void AbstractContainer::append(AbstractStorage* t)
{    
    AbstractStorage* stor = new AbstractStorage(t);
    QList<AbstractStorage*>::append( stor );
}

int AbstractContainer::size()
{
    return QList<AbstractStorage*>::size();
}

AbstractStorage* AbstractContainer::at(int i)
{
    return QList<AbstractStorage*>::at(i);
}

AbstractStorage* AbstractContainer::appendStorage(const QString &name)
{
    AbstractStorage* res = new AbstractStorage( name );
    QList<AbstractStorage*>::append(res);
    return res;
}

void AbstractContainer::removeAt(int i)
{
    AbstractStorage* stor = QList<AbstractStorage*>::at(i);
    delete stor;
    QList<AbstractStorage*>::removeAt(i);
}
